<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的收藏</span>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="favorites.length === 0" class="empty-tip">
        <el-empty description="暂无收藏"></el-empty>
      </div>

      <div v-else>
        <!-- 收藏帖子列表 -->
        <div
          v-for="favorite in favorites"
          :key="favorite.id"
          class="post-item"
        >
          <router-link :to="`/community/post/${favorite.id}`">
            <h2 class="post-title">{{ favorite.title }}</h2>
          </router-link>
          <p class="post-content">{{ favorite.content }}</p>
          
          <div class="post-meta">
            <span>
              <i class="el-icon-view"></i> {{ favorite.viewCount || 0 }}
            </span>
            <span class="post-meta-divider">|</span>
            <el-button
              type="text"
              :class="{'active-btn': favorite.isLiked}"
              @click="handleLike(favorite.id)"
            >
              <i :class="favorite.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
              {{ favorite.likeCount || 0 }}
            </el-button>
            <span class="post-meta-divider">|</span>
            <el-button
              type="text"
              :class="{'active-btn': favorite.isFavorited}"
              @click="handleFavorite(favorite.id)"
            >
              <i :class="favorite.isFavorited ? 'el-icon-collection' : 'el-icon-collection-tag'"></i>
              {{ favorite.favoriteCount || 0 }}
            </el-button>
            <span class="post-meta-divider">|</span>
            <el-button
              type="text"
              @click="handleComment(favorite.id)"
            >
              <i class="el-icon-chat-line-round"></i>
              {{ favorite.commentCount || 0 }}
            </el-button>
            
            <span class="post-time">{{ formatTime(favorite.createTime) }}</span>
          </div>
        </div>

        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange">
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import { mapGetters, mapState } from 'vuex'

export default {
  name: 'MyFavorites',
  data() {
    return {
      loading: true,
      favorites: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      username: localStorage.getItem('username') || '' // 从localStorage获取用户名
    };
  },
  computed: {
    ...mapState({
      userId: state => state.user.id,
      userName: state => state.user.name
    })
  },
  created() {
    // 添加调试日志
    console.log('用户信息:', {
      userId: this.userId,
      userName: this.userName,
      localUsername: this.username,
      token: getToken()
    });
    
    this.fetchFavorites();
  },
  methods: {
    // 获取收藏列表
    async fetchFavorites() {
      this.loading = true;
      try {
        // 优先使用本地存储的用户名，如果没有则尝试使用store中的信息
        const authValue = this.username || this.userName || this.userId.toString() || getToken();
        console.log('使用的认证值:', authValue);
        
        const response = await request({
          url: '/api/favorites/list',
          method: 'get',
          params: {
            page: this.currentPage - 1,  // 后端页码从0开始
            size: this.pageSize,
            userId: this.userId  // 添加userId作为参数
          },
          headers: {
            'Authorization': authValue
          }
        });
        
        if (response && response.posts) {
          this.favorites = response.posts;
          this.total = response.totalItems || 0;
          console.log('获取到的收藏列表:', this.favorites);
        } else {
          this.favorites = [];
          this.total = 0;
          console.log('收藏列表为空');
        }
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        this.$message.error('获取收藏列表失败，请稍后再试');
        this.favorites = [];
      } finally {
        this.loading = false;
      }
    },
    
    // 处理分页
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchFavorites();
    },
    
    // 点赞/取消点赞
    async handleLike(postId) {
      try {
        // 优先使用本地存储的用户名
        const authValue = this.username || this.userName || this.userId.toString() || getToken();
        
        const response = await request({
          url: `/api/community/posts/${postId}/like`,
          method: 'post',
          params: {
            userId: this.userId  // 添加userId作为参数
          },
          headers: {
            'Authorization': authValue
          }
        });
        
        if (response) {
          // 更新本地状态
          const post = this.favorites.find(item => item.id === postId);
          if (post) {
            post.isLiked = response.isLiked;
            post.likeCount = response.likeCount;
          }
          this.$message.success(response.isLiked ? '点赞成功' : '已取消点赞');
        }
      } catch (error) {
        console.error('点赞操作失败:', error);
        this.$message.error('点赞失败，请稍后再试');
      }
    },
    
    // 收藏/取消收藏
    async handleFavorite(postId) {
      try {
        // 优先使用本地存储的用户名
        const authValue = this.username || this.userName || this.userId.toString() || getToken();
        
        const response = await request({
          url: `/api/favorites/toggle/${postId}`,
          method: 'post',
          params: {
            userId: this.userId  // 添加userId作为参数
          },
          headers: {
            'Authorization': authValue
          }
        });
        
        if (response) {
          // 更新本地状态
          const post = this.favorites.find(item => item.id === postId);
          if (post) {
            post.isFavorited = response.isFavorited;
            post.favoriteCount = response.favoriteCount;
          }
          
          // 如果取消收藏，则从列表中移除该帖子
          if (!response.isFavorited) {
            this.favorites = this.favorites.filter(item => item.id !== postId);
            this.total -= 1;
            this.$message.success('已取消收藏');
          } else {
            this.$message.success('收藏成功');
          }
        }
      } catch (error) {
        console.error('收藏操作失败:', error);
        this.$message.error('收藏操作失败，请稍后再试');
      }
    },
    
    // 跳转到评论页面
    handleComment(postId) {
      this.$router.push(`/community/post/${postId}`);
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      
      // 小于1分钟
      if (diff < 60 * 1000) {
        return '刚刚';
      }
      // 小于1小时
      if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前';
      }
      // 小于24小时
      if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
      }
      // 小于30天
      if (diff < 30 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
      }
      
      // 大于30天，显示具体日期
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.loading-container {
  padding: 20px;
}

.empty-tip {
  padding: 50px 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.post-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.post-item:last-child {
  border-bottom: none;
}

.post-title {
  margin: 0 0 10px;
  font-size: 18px;
  color: #303133;
}

.post-content {
  margin: 0 0 10px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-meta {
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.post-meta-divider {
  margin: 0 8px;
}

.post-time {
  margin-left: auto;
}

.active-btn {
  color: #409EFF;
}
</style>
